<template>
  <!-- 面包屑导航 -->
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/users' }">用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 全局区域 -->
    <el-card class="box-card">
      <!-- 搜索栏 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="userList.query"
            @change="getUsersList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsersList"
            >
            </el-button>
          </el-input>
        </el-col>

        <!-- 新增用户按钮 -->
        <el-col :span="6">
          <el-button type="primary" plain @click="dialogVisible = true"
            >新增用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 对话框 点击新增用户按钮弹出对话框 -->
      <el-dialog
        title="请输入您新增用户的信息"
        @close="closeVal"
        :before-close="handleClose"
        :visible.sync="dialogVisible"
        width="40%"
      >
        <!-- 新增表单 -->
        <el-form ref="form" :model="form" :rules="myRules" label-width="80px">
          <el-form-item label="ID" prop="username">
            <el-input v-model="form.username"></el-input>
          </el-form-item>
          <el-form-item label="PWD" prop="password">
            <el-input v-model="form.password"></el-input>
          </el-form-item>
          <el-form-item label="Email" prop="email">
            <el-input v-model="form.email"></el-input>
          </el-form-item>
          <el-form-item label="Tel" prop="mobile">
            <el-input v-model="form.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addusers">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 对话框 点击修改用户的对话框 -->
      <el-dialog
        title="修改用户"
        @close="closeEditdialog"
        :visible.sync="editUserDialog"
        width="30%"
      >
        <el-form
          :model="editRuleForm"
          :rules="editRules"
          ref="editRuleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名">
            <el-input v-model="editRuleForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editRuleForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editRuleForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserDialog = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色 -->
      <el-dialog title="提示" :visible.sync="setRoledialogVisible" width="50%">
        <div>
          <p>当前用户:{{ currentUser.username }}</p>
          <p>当前用户:{{ currentUser.role_name }}</p>
        </div>
        <p>
          分配的角色:
          <el-select v-model="selectRoled" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoledialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRoled">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 表格区域 -->
      <el-table :data="list" border style="width: 100%">
        <el-table-column label="#" type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <!-- 状态列 -->
        <el-table-column prop="mg_state" width="100px" label="状态">
          label="状态">
          <template slot-scope="ele">
            <el-switch v-model="ele.row.mg_state" @change="zhuangtai(ele.row)">
            </el-switch>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column width="165px" label="操作">
          <template slot-scope="{ row }">
            <!-- 修改按钮 -->
            <el-button
              @click="showEdit(row.id)"
              type="primary"
              icon="el-icon-edit"
              circle
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              @click="deleteUser(row.id)"
              icon="el-icon-delete-solid"
              circle
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-s-tools"
              circle
              @click="showSetRole(row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="pageSizeChange"
        @current-change="pageNumChange"
        :current-page="userList.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="userList.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
export default {
  name: 'app',
  data () {
    const mobleRuler = (myRules, value, cb) => {
      const p = /^1[3|5|7|8|9]\d{9}$/
      if (p.test(value)) return cb()
      cb(new Error('请输入合法手机号'))
    }
    return {
      // switch开关的布尔值
      // 点击弹出对话框
      dialogVisible: false,
      // 用户数据请求参数对象
      userList: {
        query: '', // 查询参数
        pagenum: 1, // 当前页码
        pagesize: 2 // 页容量
      },
      // 列表数据
      list: [],
      total: 0,
      pagenum: 0,
      // 表单验证规则对象
      myRules: {
        username: [
          {
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            type: 'email',
            message: '请输入正确的邮箱',
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          },
          { validator: mobleRuler, trigger: 'blur' }
        ]
      },
      form: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editUserDialog: false,
      // 用来保存根据id获取 到的用户数据
      editRuleForm: {},
      setRoledialogVisible: false,
      editRules: {
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            type: 'email',
            message: '请输入正确的邮箱',
            trigger: 'blur'
          }
        ],
        mobile: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          },
          { validator: mobleRuler, trigger: 'blur' }
        ]
      },
      currentUser: {},
      roleList: [], // 角色列表
      selectRoled: '' // 选中的角色id

    }
  },
  methods: {
    async setRoled () {
      console.log(this.selectRoled)
      // 请求
      await this.$http.put(`users/${this.currentUser.id}/role`, {
        rid: this.selectRoled
      })
      this.$message({
        message: '修改成功!',
        type: 'success',
        showClose: true,
        duration: 3000
      })
      // 刷新列表
      this.getUsersList()
      // 关闭对话框
      this.setRoledialogVisible = false
    },
    async showSetRole (row) {
      this.currentUser = row
      this.setRoledialogVisible = true
      const { data: res } = await this.$http.get('roles')
      this.roleList = res.data
    },
    // 根据id 删除用户
    deleteUser (id) {
      this.$confirm('您确定要删除吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(async action => {
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) return this.$message.error('删除失败!')
        this.getUsersList()
        this.$message({
          message: '删除成功!',
          type: 'success',
          showClose: true,
          duration: 3000
        })
      }).catch(() => {
        // 有bug
      })
    },
    // 修改用户
    editUser () {
      this.$refs.editRuleForm.validate(async isOk => {
        if (!isOk) return false
        // console.log('isOk')
        const { data: res } = await this.$http.put('users/' + this.editRuleForm.id,
          {
            email: this.editRuleForm.email,
            mobile: this.editRuleForm.mobile
          })
        if (res.meta.status !== 200) {
          return this.$message({
            message: '修改失败!',
            type: 'error',
            showClose: true,
            duration: 3000
          })
        }
        this.$message({
          message: '修改成功',
          type: 'success',
          showClose: true,
          duration: 3000
        })
        this.editUserDialog = false
      })
    },
    closeEditdialog () {
      this.$refs.editRuleForm.resetFields()
    },
    async showEdit (id) {
      this.editUserDialog = true
      // 根据id查询用户数据
      const { data: res } = await this.$http.get('users/' + id)
      // console.log(res/)
      this.editRuleForm = res.data
      // console.log(res)
    },
    // 弹出一个询问是否关闭对话框的提示消息
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    // 点击退出对话框清除页面所有内容
    closeVal () {
      this.$refs.form.resetFields()
    },
    // 状态改变事件
    async zhuangtai (isChange) {
      const { data: res } = await this.$http.put(
        `users/${isChange.id}/state/${isChange.mg_state}`
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 状态改变成功 应该给个提示
      this.$message.success(res.meta.msg)
    },
    // 用户数据查询事件
    async getUsersList () {
      const { data: res } = await this.$http.get('users', {
        params: this.userList
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 成功就将数据赋值费this.list
      console.log(res)
      this.list = res.data.users
      this.total = res.data.total
    },
    // pageSize 改变时会触发 页页容量
    pageSizeChange (newpagesize) {
      console.log(newpagesize)
      this.userList.pagesize = newpagesize
      this.getUsersList()
    },
    // 当前页码
    pageNumChange (newPagenum) {
      console.log(newPagenum)
      this.userList.pagenum = newPagenum
      this.getUsersList()
    },
    // 新增用户
    addusers () {
      this.$refs.form.validate(async isOk => {
        // 如果失败 return
        if (!isOk) return
        // 异步请求
        const { data: res } = await this.$http.post('users', this.form)
        if (res.meta.status !== 201) this.$message.error('添加用户失败!')
        // 添加成功 重新渲染列表
        this.getUsersList()
        this.$message.success('添加用户成功!')
        // 关闭对话框
        this.dialogVisible = false
      })
    }
  },
  // 钩子函数 页面创建时异步请求用户数据
  created () {
    this.getUsersList()
  }
}
</script>

<style scoped lang="less"></style>
